//
//  HNEffectCache.m
//  HeroNuts
//
//  Created by Vicky on 6/7/11.
//  Copyright 2011 Tongji University. All rights reserved.
//

#import "HNEffectCache.h"
#import "cocos2d.h"
#import "CJSONDeserializer.h"


@implementation HNEffectCache

static HNEffectCache* sharedEffectCache_ = nil;

+(id)sharedEffectCache
{
	if (!sharedEffectCache_)
        sharedEffectCache_ = [[HNEffectCache alloc] init];
    
	return sharedEffectCache_;
}

+(id)alloc
{
	NSAssert(sharedEffectCache_ == nil, @"Attempted to allocate a second instance of a singleton.");
	return [super alloc];
}


-(void)addEffectWithFile:(NSString*)plist
{
	[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:plist];
}

- (id)effectByName:(NSString*)effectName
{
	CCAnimate *effect = [effects_ objectForKey:effectName];
	if (effect) 
	{
		return effect;
	}
	else 
	{
		CGFloat delay = [(NSNumber*)[self objectFromJson:effectName key:@"FrameDelay"] floatValue];
		NSArray* frameNames = [self objectFromJson:effectName key:@"Frames"];
		
		
		NSMutableArray *animFrames = [NSMutableArray arrayWithCapacity:20];
		
		for (NSString *name in frameNames) {
			CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:name];
			[animFrames addObject:frame];
		}
		
		//CGFloat delay = [[HNActorInfoCache sharedActorInfoCache] frameDelayByActor:actorType];
		CCAnimation *animation = [CCAnimation animationWithFrames:animFrames delay:delay];
		effect = [CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO];
		[effects_ setObject:effect forKey:effectName];
		
		return effect;
		
	}
}

- (id)objectFromJson:(NSString*)json key:(NSString*)key
{
	NSString *filePath; 
	
	filePath = [[NSBundle mainBundle] pathForResource:json ofType:@"json"];
	
	NSAssert(filePath,@"filePath == nil");
	
	NSData *jsonData = [[NSFileManager defaultManager] contentsAtPath:filePath];	
	
	CJSONDeserializer *jsonDeserializer = [CJSONDeserializer deserializer];
	NSError *error = nil;
	NSDictionary *effectInfo = [jsonDeserializer deserializeAsDictionary:jsonData error:&error];
	if (error) {
		//handle Error, didn't have here.
	}
	
	return [effectInfo objectForKey:key];
}


- (NSString *)firstFrameNameOfEffect:(NSString *)effect
{
	return [self objectFromJson:effect key:@"FirstFrame"];
}

- (CGPoint)originalPositionOfEffect:(NSString *)effect
{
    NSNumber *x = [self objectFromJson:effect key:@"x"];
	NSNumber *y = [self objectFromJson:effect key:@"y"];
	return CGPointMake([x floatValue], [y floatValue]);
}


@end
